﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using ICSharpCode.SharpZipLib.Zip;

namespace Microsoft.WowAddonStudio.Project.Import.Ace
{
	/// <summary>
	/// Implements import from ace packages.
	/// </summary>
	public class AceImportPlugin : IImportPlugin
	{
		private string rootDirectoryName;

		#region IImportPlugin Members

		/// <summary>
		/// Gets the user interface element used to pick the uri to import from.
		/// </summary>
		/// <returns>
		/// An instance of the <see cref="ImportWizardPane"/> class.
		/// </returns>
		public ImportWizardPane GetImportWizardPane()
		{
			return new PackageSelectorPane();
		}

		/// <summary>
		/// Imports the addon at the given uri.
		/// </summary>
		/// <param name="importSettings">The import settings.</param>
		/// <returns>
		/// An enumerable collection of <see cref="IAddonItem"/>s.
		/// </returns>
		public IEnumerable<IAddonItem> Import(object importSettings)
		{
			if (importSettings == null)
				throw new ArgumentNullException("importSettings");
			if (!(importSettings is AceImportSettings))
				throw new ArgumentException("Import settings type mismatch.", "importSettings");

			var aceImportSettings = (AceImportSettings) importSettings;
			string filePath = DownloadAcePackage(aceImportSettings);

			TempFileContainer.Instance.AddTempFilePath(filePath);

			var addonItems = new List<IAddonItem>();


			rootDirectoryName = Path.GetFileNameWithoutExtension(filePath);
			using (ZipFile zipFile = new ZipFile(filePath))
			{
				for (int i = 0; i < zipFile.Count; ++i)
				{
					ZipEntry entry = zipFile[i];

					if (entry.IsFile)
					{
						addonItems.Add(CreateAddonItem(filePath, entry));
					}
				}
			}

			return addonItems;
		}

		/// <summary>
		/// Gets the name of the root directory. Used when the import process
		/// (<see cref="ImportProcess"/>) creates subdirectory under the target
		/// folder based on the value of this property.
		/// </summary>
		/// <value>The name of the root directory.</value>
		public string RootDirectoryName
		{
			get { return rootDirectoryName; }
		}

		#endregion

		#region Private member functions

		/// <summary>
		/// Creates the addon item.
		/// </summary>
		/// <param name="filePath">The file path.</param>
		/// <param name="entry">The entry.</param>
		/// <returns></returns>
		private static IAddonItem CreateAddonItem(string filePath, ZipEntry entry)
		{
			string directoryName = Path.GetDirectoryName(entry.Name);
			string fileName = Path.GetFileName(entry.Name);
			string relativePath = Path.Combine(directoryName, fileName);
			relativePath = relativePath.Substring(relativePath.IndexOf(Path.DirectorySeparatorChar) + 1);
			return new AceAddonItem(relativePath, filePath, entry.Name);
		}

		/// <summary>
		/// Downloads the ace package.
		/// </summary>
		/// <param name="aceImportSettings">The ace import settings.</param>
		/// <returns></returns>
		private static string DownloadAcePackage(AceImportSettings aceImportSettings)
		{
			string filePath;
			//Download zip file
			using (WebClient client = new WebClient())
			{
				//TODO: authentication???
				client.Proxy = WebRequest.DefaultWebProxy;

				filePath = Path.Combine(Path.GetTempPath(),
				                        Path.GetFileName(aceImportSettings.SourceUri.AbsolutePath));

				using (File.Create(filePath))
				{
				}
				client.DownloadFile(aceImportSettings.SourceUri.AbsoluteUri,
				                    filePath);
			}
			return filePath;
		}

		#endregion
	}
}